import styles from './index.module.scss'
import Icon from '@/components/Icon'
import NavBar from '@/components/NavBar'
import { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { getArticleDetail } from '@/store/action/article'
import { useParams } from 'react-router'
import { useAppSelector } from '@/store'
import { sanitize } from 'dompurify'
import dayjs from 'dayjs'
import Skeleton from './components/Skeleton'
import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'
import ArticleFooter from './components/ArticleFooter'
import NoComment from './components/NoComment'
import CommentItem from './components/CommentItem'
import { getComments } from '@/store/action/comment'
import { Popup, Toast } from 'antd-mobile'
import Share from './components/Share'
import { changeUserFollowings } from '@/store/action/user'
import classNames from 'classnames'
import CommentInput from './components/CommentInput'

export default function Article() {
  const dispatch = useDispatch()

  // 🔔 useParams 函数需要指定泛型确定 params 对象的格式
  const params = useParams<{ id: string }>()
  // console.log(params.id)

  const { detail } = useAppSelector((state) => state.article)
  const { comments } = useAppSelector((state) => state.comment)

  useEffect(() => {
    // 获取文章的详情
    dispatch(getArticleDetail(params.id))
  }, [dispatch, params.id])

  useEffect(() => {
    // 文章还没加载完毕，先不处理
    if (!detail.art_id) return
    // console.log('加载完毕了，需要高亮处理', detail.art_id)
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    })

    // 查找容器元素下符合 pre code 选择器规则的子元素，进行高亮
    const codes = document.querySelectorAll('.dg-html pre')
    if (codes.length > 0) {
      return codes.forEach((el: any) => hljs.highlightElement(el))
    }
  }, [detail.art_id])

  const [showAuthor, setShowAuthor] = useState(false)
  // 作者信息 DOM
  const authorRef = useRef<HTMLDivElement>(null)
  // 滚动事件处理函数
  const handleScroll = () => {
    // 获取元素在可视区的滚动距离
    // 普通非空断言  as HTMLDivElement
    // if ((authorRef.current as HTMLDivElement).getBoundingClientRect().y < 0) {
    // 非空断言简写  感叹号!
    if (authorRef.current!.getBoundingClientRect().y < 0) {
      setShowAuthor(true)
    } else {
      setShowAuthor(false)
    }
  }

  useEffect(() => {
    // 获取文章的评论列表
    dispatch(getComments({ source: params.id }))
  }, [dispatch, params.id])

  const wrapperRef = useRef<HTMLDivElement>(null)
  const commemtHeadRef = useRef<HTMLDivElement>(null)
  // 准备开关变量，用于切换是否滚动到评论区
  const isShowComment = useRef(false)
  const onShowComment = () => {
    isShowComment.current = !isShowComment.current
    // 计算评论区的距离
    const top = commemtHeadRef.current!.offsetTop - commemtHeadRef.current!.offsetHeight
    wrapperRef.current?.scrollTo({
      // 🧐 通过开关思想：切换滚动到评论区和返回顶部
      top: isShowComment.current ? top : 0,
    })
  }

  // 分享功能
  const [share, setShare] = useState(false)
  const onCloseShare = () => {
    setShare(false)
  }

  // 关注功能
  const handleFollow = async () => {
    await dispatch(changeUserFollowings(detail.aut_id))
    Toast.show({
      content: detail.is_followed ? '已取消关注' : '关注成功',
      maskClickable: false,
      duration: 1000,
    })
  }

  // 添加评论的显示和隐藏
  const [showComment, setShowComment] = useState(false)
  const closeComment = () => {
    setShowComment(false)
  }

  return (
    <div className={styles.root}>
      <div className='root-wrapper'>
        {/* 顶部导航栏 */}
        <NavBar right={<Icon type='icongengduo' onClick={() => setShare(true)} />}>
          {showAuthor ? (
            <div className='nav-author'>
              <img src={detail.aut_photo} alt='' />
              <span className='name'>{detail.aut_name}</span>
              <span
                className={classNames('follow', detail.is_followed ? 'followed' : '')}
                onClick={handleFollow}
              >
                {detail.is_followed ? '已关注' : '+关注'}
              </span>
            </div>
          ) : (
            <>文章详情</>
          )}
        </NavBar>
        {/* 文章主体 */}
        <div className='wrapper' ref={wrapperRef} onScroll={handleScroll}>
          <div className='article-wrapper' hidden={!!detail.art_id}>
            {/* 骨架屏占位效果 */}
            <Skeleton />
          </div>
          <div className='article-wrapper' hidden={!detail.art_id}>
            {/* 文章描述信息栏 */}
            <div className='header'>
              <h1 className='title'>{detail.title}</h1>

              <div className='info'>
                <span>{dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}</span>
                <span>{10} 阅读</span>
                <span>{detail.comm_count} 评论</span>
              </div>

              {/* 作者信息 - 滚动出去到可视区外，头部显示作者信息*/}
              <div className='author' ref={authorRef}>
                <img src={detail.aut_photo} alt='' />
                <span className='name'>{detail.aut_name}</span>
                <span
                  className={classNames('follow', detail.is_followed ? 'followed' : '')}
                  onClick={handleFollow}
                >
                  {detail.is_followed ? '已关注' : '+关注'}
                </span>
              </div>
            </div>

            {/* 文章正文内容区域 */}
            <div className='content'>
              <div
                className='content-html dg-html'
                // 💥 dompurify.sanitize() 对 HTML 内容进行净化，防止 XSS 攻击
                dangerouslySetInnerHTML={{ __html: sanitize(detail.content) }}
              />
              <div className='date'>
                发布文章时间：{dayjs(detail.pubdate).format('YYYY-MM-DD hh:mm:ss')}
              </div>
            </div>
            <div className='divider'></div>
            <div className='comment'>
              {/* 评论总览信息 */}
              <div className='comment-header' ref={commemtHeadRef}>
                <span>全部评论（{detail.comm_count}）</span>
                <span>{detail.like_count} 点赞</span>
              </div>

              {/* 评论列表 */}
              {comments.results?.length === 0 ? (
                <NoComment />
              ) : (
                comments.results?.map((item) => <CommentItem key={item.com_id} comment={item} />)
              )}
            </div>
          </div>
        </div>
        {/* 文章底部 */}
        <ArticleFooter
          onShowComment={onShowComment}
          onComment={() => setShowComment(true)}
          onShare={() => setShare(true)}
        />
        {/* 分享抽屉 */}
        <Popup
          position='bottom'
          bodyStyle={{ backgroundColor: 'transparent' }}
          visible={share}
          onMaskClick={onCloseShare}
        >
          <Share onClose={onCloseShare} />
        </Popup>
        {/* 评论抽屉 */}
        <Popup
          className='drawer'
          position='bottom'
          visible={showComment}
          onMaskClick={closeComment}
        >
          {showComment && <CommentInput onClose={closeComment} />}
        </Popup>
      </div>
    </div>
  )
}
